//
//  DMMyOrderVC.m
//  DistributionMall
//
//  Created by JHnoplan on 2018/10/16.
//  Copyright © 2018年 JHnoplan. All rights reserved.
//

#import "DMMyOrderVC.h"
#import "FDSlideBar.h"
#import "DMMyOrderCell.h"
#import "DMAlertView.h"
#import "DMMyOrderDetailVC.h"
#import "DMMyOrderCommentVC.h"
#import "UIScrollView+EmptyDataSet.h"
#import "DMSelectPayWayVC.h"
#import "DMMyOrderLogisticsVC.h"


//model
#import "KDisOrderModel.h"

#import "KStoreRequest.h"

@interface DMMyOrderVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (nonatomic, strong) FDSlideBar *sliderBar;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic,assign) KMineOrderType type;

@property (nonatomic,assign) NSInteger page;
@end

@implementation DMMyOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self startInit];
}

-(void)startInit {
    self.navigationItem.title = @"我的订单";
    self.view.backgroundColor = DMDefaultColor;
    _dataArray = [NSMutableArray new];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.type = self.index;
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"DMMyOrderCell" bundle:nil] forCellReuseIdentifier:@"DMMyOrderCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadmore)];
    [self.tableView.mj_header beginRefreshing];
    //头部选择View
    [self makeSlideBar];
}

#pragma mark ----netWork----

-(void)refresh{
    NSString * typeStr;
    switch (self.type) {
        case KMineOrderTypeAll:
            typeStr = @"all";
            break;
        case KMineOrderTypeWaitPay:
            typeStr = @"awaiting_pay";
            break;
        case KMineOrderTypeWaitSend:
            typeStr = @"awaiting_ship";
            break;
        case KMineOrderTypeWaitTake:
            typeStr = @"shipped";
            break;
        case KMineOrderTypeWaitEvaluation:
            typeStr = @"completed";
            break;
        default:
            break;
    }
    
    KStoreRequest * request = [[KStoreRequest alloc]initStoreOrderListWithPage:1 soStatus:typeStr];
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        weakSelf.page = 1;
        
        KDisOrderListModel * listModel = [KDisOrderListModel modelWithJSON:baseModel.data];
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.dataArray addObjectsFromArray:listModel.soEntityViews];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header endRefreshing];
        
    } failure:^(KBaseModel *errorModel) {
        [JLProgressHUDManager showErrorHud:errorModel.msg];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
-(void)loadmore{
    self.page++;
    NSString * typeStr;
    switch (self.type) {
        case KMineOrderTypeAll:
            typeStr = @"all";
            break;
        case KMineOrderTypeWaitPay:
            typeStr = @"awaiting_pay";
            break;
        case KMineOrderTypeWaitSend:
            typeStr = @"awaiting_ship";
            break;
        case KMineOrderTypeWaitTake:
            typeStr = @"shipped";
            break;
        case KMineOrderTypeWaitEvaluation:
            typeStr = @"completed";
            break;
        default:
            break;
    }
    
    KStoreRequest * request = [[KStoreRequest alloc]initStoreOrderListWithPage:self.page soStatus:typeStr];
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        
        
        KDisOrderListModel * listModel = [KDisOrderListModel modelWithJSON:baseModel.data];
        
        [weakSelf.dataArray addObjectsFromArray:listModel.soEntityViews];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        
    } failure:^(KBaseModel *errorModel) {
        weakSelf.page--;
        [JLProgressHUDManager showErrorHud:errorModel.msg];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

-(void)deleteOrderWithModel:(KDisOrderModel*)model{
    
    
    KStoreRequest * request = [[KStoreRequest alloc]initStoreCancelOrderWithKey:model.id];
    
    [JLProgressHUDManager showLoadingHud];
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        
        [JLProgressHUDManager showSuccessHud:@"取消订单成功"];
        [weakSelf.dataArray removeObject:model];
        [weakSelf.tableView reloadData];
        
    } failure:^(KBaseModel *errorModel) {
        
        [JLProgressHUDManager showErrorHud:errorModel.msg];
        
    }];
}

#pragma mark ----tableview----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDisOrderModel * model  = self.dataArray[indexPath.section];
    if ([model.soStatus isEqualToString:@"awaiting_ship"]) {
        return 129;
    }
    return 168;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DMMyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DMMyOrderCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"DMMyOrderCell" owner:self options:nil].firstObject;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    KDisOrderModel * model  = self.dataArray[indexPath.section];
    
    cell.model = model;
    MJWeakSelf
    [cell setClickButton:^(NSString *title) {
        if ([title isEqualToString:@"去评价"]) {
            DMMyOrderCommentVC *vc = [DMMyOrderCommentVC new];
            vc.model = model;
            MJWeakSelf
            [vc setReloadBlock:^{
                [weakSelf.tableView.mj_header beginRefreshing];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([title isEqualToString:@"删除订单"]||[title isEqualToString:@"取消订单"]) {
            DMAlertView *alertView = [[DMAlertView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
            [self.navigationController.view addSubview:alertView];
            [alertView showAlertViewWithTitle:@"您确认取消该订单吗" status:2];
            MJWeakSelf
            [alertView setSureBlock:^{
                [weakSelf deleteOrderWithModel:model];
            }];
        }else if ([title isEqualToString:@"查看物流"]) {
            DMMyOrderLogisticsVC  * vc = [[DMMyOrderLogisticsVC alloc]init];
            vc.soEntityId = model.id;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        }else if ([title isEqualToString:@"确认收货"]) {
            
            KStoreRequest * request = [[KStoreRequest alloc]initStoreConfirmReceiptWithKey:model.id];
            MJWeakSelf
            [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
                
                [JLProgressHUDManager showSuccessHud:@"已确认收货"];
                
                [weakSelf.dataArray removeObject:model];
                [weakSelf.tableView reloadData];
                
                
            } failure:^(KBaseModel *errorModel) {
                [JLProgressHUDManager showErrorHud:errorModel.msg];
            }];
            
            
        }else if ([title isEqualToString:@"去支付"]) {
            DMSelectPayWayVC * vc = [[DMSelectPayWayVC alloc]init];
            vc.entityid = model.id;
            vc.payPrice = model.total.doubleValue;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DMMyOrderDetailVC *vc = [DMMyOrderDetailVC new];
//    DMMyOrderCommentVC *vc = [DMMyOrderCommentVC new];
    KDisOrderModel * model  = self.dataArray[indexPath.section];

    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
    
}

//头部选择View
-(void)makeSlideBar {
    _sliderBar = [[FDSlideBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 45)];
    _sliderBar.itemsTitle = @[@"全部", @"待支付", @"待发货", @"待收货", @"已完成"];
    _sliderBar.backgroundColor = [UIColor clearColor];
    _sliderBar.itemColor = DMFontColor;
    _sliderBar.itemSelectedColor = DMMainColor;
    _sliderBar.sliderColor = DMMainColor;
    [_sliderBar selectSlideBarItemAtIndex:_index];
    MJWeakSelf
    [_sliderBar slideBarItemSelectedCallback:^(NSUInteger idx) {
        //选择,刷新tableView
        weakSelf.type = idx;
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    [_headView addSubview:_sliderBar];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 44, ScreenWidth, 1)];
    line.backgroundColor = RGBCOLOR(237, 237, 237);
    [_headView addSubview:line];
}

#pragma mark - DZNEmptyDataSetSource
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wudingdan"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"您还没有订单，快前往商城购买吧";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:18],
                                 NSForegroundColorAttributeName:RGBCOLOR(119, 165, 232)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    NSString *buttonTitle = @"前往商城";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:DMFontSize(16),
                                 NSForegroundColorAttributeName:DMWhiteColor
                                 };
    return [[NSAttributedString alloc] initWithString:buttonTitle attributes:attributes];
}
-(void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    self.tabBarController.selectedIndex = 0;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
